package com.congee02.sw.var;

import java.util.Arrays;

public class MaxFrequency {

    public int maxFrequency(int[] nums, int k) {

        int n = nums.length;
        Arrays.sort(nums);

        // l = r = 0
        long sum = 0;
        int ans = 1;

        int l = 0;
        for (int r = 0 ; r < n ; r ++ ) {
            sum += nums[r];

            while ((long) nums[r] * (r - l + 1) - sum > k) {
                sum -= nums[l ++];
            }

            ans = Math.max(ans, r - l + 1);
        }

        return ans;
    }

}
